function url = S3QLSyntax(S)
%function url = S3QLSyntax(S)
%Syntax: S3QLSyntax(S) reads parameters on the struct S and
%build a query for S3QL based on existing fields
%INPUTS: S is a struct with at least fields url, key and project_id. All
%other parameters to be queried must be fieldnames of S. A fieldname can
%also be a struct, in that case nested tags must the fieldnames of that
%struct

%Helena F Deus (helenadeus@gmail.com), 22 March 2007


Sfields = fieldnames(S);
if isstruct(S)
    if isfield(S, 'url')
    %if isfield(S, 'url') && isfield(S, 'key')
    if ~(S.url(end)=='/')
    S.url = [S.url, '/'];
    end
    if isfield(S,'key')
    url = [S.url, 'S3QL.php?query=<S3QL><key>', S.key, '</key>'];
    S = rmfield(S,'key');
    else
        url = [S.url, 'S3QL.php?query=<S3QL>'];
    end
        
        
        if(length(fieldnames(S))>=2)
        
        %read each first level fields int he struct, but first remove the
        %used fields url and key
        Z=S;Z=rmfield(Z, {'url'});
        Zfields = fieldnames(Z);
        for i=1:length(fields(Z))
            
            url = strcat(url, '<', Zfields(i),'>');
            
            %read nested fields in teh struct
            if isstruct(Z.(Zfields{i}))
            subfieldNames = fieldnames(Z.(Zfields{i}));
                for j=1:length(subfieldNames)
                
                try
                    url = strcat(url, '<', subfieldNames{j},'>', Z.(Zfields{i}).(subfieldNames{j}), '</', subfieldNames{j},'>');
                catch
                    try
                        url = strcat(url, '<', subfieldNames{j},'>', num2str(Z.(Zfields{i}).(subfieldNames{j})), '</', subfieldNames{j},'>');
                    catch
                        
                    disp 'ups'
                    end
                end
                end
                
            else
                url = strcat(url, Z.(Zfields{i}));
            end
                url = strcat(url, '</', Zfields(i),'>');
            end
        end
            url = strcat(url, '</S3QL>');
    else
        disp('Struct does not have the required fields');
        return;
    end
end

%finito
if(size(url,2)==1)
url = url{1};
end